import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:xrp/xrp.dart';


import 'package:on_chain/on_chain.dart';
import 'package:blockchain_utils/blockchain_utils.dart';
// import 'package:on_chain/';
import 'package:example/example/tron/provider_service/provider_service.dart';
import  'package:example/example/tron/intract_with_http_node/custom_request_example.dart' as OtherTronRequestGetAccountBalance;


void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // final xrpAddress = xrpDetails.address;
  // final xrpPrivateKey = xrpDetails.privateKey;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);



  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var balance = 0;
  var receiveBalance = 0;



  @override
  Widget build(BuildContext context) {


    return Scaffold(
      appBar: AppBar(
        title: const Text('XRP'),
      ),
      body:
          Column(children: [
            Text("send"),
            Text(balance.toString()),
            Text("receive"),
            Text(receiveBalance.toString()),
            SizedBox(
              width: 100,
              height: 50,
              child: ElevatedButton(
                onPressed: () async {

                  // TRX
                  /// Generate a 12-word mnemonic phrase.
                  final mnemonic =
                  Bip39MnemonicGenerator().fromWordsNumber(Bip39WordsNum.wordsNum12);

                  final mnemonic1 = Mnemonic.fromString('draw clock public inform gather exile cannon empower prefer trend patient inner');
                  // draw clock public inform gather exile cannon empower prefer trend patient inner

                  final seed = Bip39SeedGenerator(mnemonic1).generate("");

                  // BytesUtils.fromBinary(seed);

                  final tronCoin = Bip44Coins.tron;
                  final seedStr = BytesUtils.toHexString(seed);

                  final tronDefaultPath = Bip44.fromSeed(seed, tronCoin).deriveDefaultPath;
                  final tronPrivateKey =
                  TronPrivateKey.fromBytes(tronDefaultPath.privateKey.raw);
                  // privatekey: ee470...
                  // publicKey: 02b54d3bf32beab10f799107c9ebbc14080e41f94bb8a38185577e6d4e9576fae0
                  // TT5psqaojok3D32KwC68Gzi57paXR5FHeB
                  // final TronPrivateKey tronPrivateKey = TronPrivateKey("...");
                  final TronPublicKey tronPublicKey = tronPrivateKey.publicKey();
                  final TronAddress tronAddress = tronPublicKey.toAddress();
                  final String base58TronAddress = tronAddress.toString(true);
                  final String hexTronAddress = tronAddress.toString(false);


                  final rpc = TronProvider(TronHTTPProvider(url: "https://api.trongrid.io"));

                  // final rpc1 = TronProvider(TronHTTPProvider(url: "https://api.trongrid.io"));
                  final balance = await rpc.request(OtherTronRequestGetAccountBalance.TronRequestGetAccountBalance(address: TronAddress('TT5psqaojok3D32KwC68Gzi57paXR5FHeB')));

                  final String hexTronAddress1 = tronAddress.toString(false);



                  final seed1 = BytesUtils.fromHexString(seedStr);
                  final bip44 = Bip44.fromSeed(seed1, Bip44Coins.tron);
                  // final prv = TronPrivateKey.fromBytes(bip44.privateKey.raw);
                  // tronPrivateKey
                  final prv = tronPrivateKey;
                  final publicKey = prv.publicKey();
                  final address = publicKey.toAddress();
                  final receiverAddress = TronAddress("TK9Ga3QCVMcqsuPXG9HV1EVQ85GP5u6Mck");

                  /// intialize shasta http provider to send and receive requests
                  // final rpc =
                  // TronProvider(TronHTTPProvider(url: "https://api.shasta.trongrid.io"));

                  /// create transfer contract (TRX Transfer)
                  final transferContract = TransferContract(
                    /// 10 TRX
                    amount: TronHelper.toSun("5"),
                    ownerAddress: address,
                    toAddress: receiverAddress,
                  );

                  /// validate transacation and got required data like block hash and ....
                  final request = await rpc.request(TronRequestCreateTransaction.fromContract(

                    /// params: permission ID (multi-sig Transaction), optional data like memo
                      transferContract,
                      visible: false));

                  /// An error has occurred with the request, and we need to investigate the issue to determine what is happening.
                  if (!request.isSuccess) {
                    /// print(request.error ?? request.respose);
                    return;
                  }

                  /// get transactionRaw from response and make sure sed fee limit
                  final rawTr =
                  request.transactionRaw!.copyWith(feeLimit: BigInt.from(10000000));

// txID
                  final _ = rawTr.txID;

                  /// get transaaction digest and sign with private key
                  final sign = prv.sign(rawTr.toBuffer());

                  /// create transaction object and add raw data and signature to this
                  final transaction = Transaction(rawData: rawTr, signature: [sign]);

                  /// get raw data buffer
                  final raw = BytesUtils.toHexString(transaction.toBuffer());

                  /// send transaction to network
                  await rpc.request(TronRequestBroadcastHex(transaction: raw));



                  // final balance = await rpc.request(OtherTronRequestGetAccountBalance(
                  //     address: TronAddress("TMcbQBuj5ATtm9feRiMp6QRd587hT7HHyU")));


                  // final accountInfo = await rpc.request(TronRequestGetAccount(
                  //     address: TronAddress("TMcbQBuj5ATtm9feRiMp6QRd587hT7HHyU")));
                  //
                  // final accountResource = await rpc.request(TronRequestGetAccountResource(
                  //     address: TronAddress("TMcbQBuj5ATtm9feRiMp6QRd587hT7HHyU")));
                  //
                  // final chainParameters = await rpc.request(TronRequestGetChainParameters());
                  // final block = await rpc.request(TronRequestGetNowBlock());

                  // TT5psqaojok3D32KwC68Gzi57paXR5FHeB



                  // final mnemonic = XRP.generateMnemonic();
                  // final mnemonicReceiver = XRP.generateMnemonic();




                  //
                  // final mnemonic = "crumble day model strong upon faint lend race limit index visa sadness";
                  // // final mnemonicReceiver = "move human someone behind pigeon path frozen disease prison latin spell rotate";
                  //
                  //
                  // if (kDebugMode) {
                  //   print("mnemonic: $mnemonic");
                  // }
                  // // if (kDebugMode) {
                  // //   print("mnemonicReceiver: $mnemonicReceiver");
                  // // }
                  //
                  // XRPAccount xrpDetails = XRP.fromMnemonic(mnemonic);
                  // // XRPAccount xrpDetailsReceiver = XRP.fromMnemonic(mnemonicReceiver);
                  //
                  //
                  // final xrpAddress = xrpDetails.address;
                  // final xrpPrivateKey = xrpDetails.privateKey;
                  // if (kDebugMode) {
                  //   print("Sender Address: $xrpAddress");
                  //   print("Sender Private Key: $xrpPrivateKey");
                  //
                  //   // print("Receiver Address: ${xrpDetailsReceiver.address}");
                  //   // print("Receiver Private Key: ${xrpDetailsReceiver.privateKey}");
                  // }
                  //
                  // bool isValidXRPAddress = XRP.isValidAddress(xrpAddress);
                  // if (kDebugMode) {
                  //   print("isValidXRPAddress: $isValidXRPAddress");
                  // }
                  // // bool getTestnetFaucet = await XRP.fundRippleTestnet(xrpAddress);
                  // // if (kDebugMode) {
                  // //   print("Funded: $getTestnetFaucet");
                  // // }
                  // int getDrops = await XRP.getBalance(xrpAddress, XRPCluster.mainNet);
                  // setState(() {
                  //   balance = getDrops;
                  // });
                  // if (kDebugMode) {
                  //   print("Sender account balance Before Sending: $getDrops");
                  // }
                  //
                  // String txHash = await XRP.transferToken(
                  //   amount: '1',
                  //   // to: xrpDetailsReceiver.address,
                  //   to: "rNxp4h8apvRis6mJf9Sh8C6iRxfrDWN7AV",
                  //   account: xrpDetails,
                  //   networkType: XRPCluster.mainNet,
                  //     destinationTag: 446338490,
                  // );
                  // //
                  // if (kDebugMode) {
                  //   print("txHash: $txHash");
                  // }
                  //
                  // int getDropsAfterSend =
                  // await XRP.getBalance(xrpAddress, XRPCluster.mainNet);
                  //
                  //
                  // var record =
                  // await XRP.getRecord(xrpAddress, XRPCluster.mainNet);
                  //
                  // if (kDebugMode) {
                  //   print("Sender account balance After Sending: $getDropsAfterSend");
                  // }
                  //
                  // // int getDropsAfterSendReceiver = await XRP.getBalance(
                  // //     xrpDetailsReceiver.address, XRPCluster.mainNet);
                  // int getDropsAfterSendReceiver = await XRP.getBalance(
                  //     "rNxp4h8apvRis6mJf9Sh8C6iRxfrDWN7AV", XRPCluster.mainNet);
                  //
                  //
                  // if (kDebugMode) {
                  //   setState(() {
                  //     this.receiveBalance = getDropsAfterSendReceiver;
                  //   });
                  //   print("Receiver account balance: $getDropsAfterSendReceiver");
                  // }
                },
                child: const Text('click me'),
              ),
            )
          ],)

    );
  }
}
